<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="学习任务名称" prop="taskName" >
            <el-input placeholder="请输入学习任务名称" v-model="state.queryForm.taskName" />
          </el-form-item>
          <el-form-item label="参与组织" prop="orgName">
            <el-cascader v-model="state.queryForm.orgNames"  style="width: 420px" placeholder="请选择" @change="handleChange" ref="cascadertasklist"
             :props="{ value: 'id', label: 'name', children: 'children',checkStrictly: true ,}" :options="options1" clearable filterable>
            </el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button icon="folder-add" type="primary" class="ml10" @click="goKszlFile(0)" v-auth="'train_xxrwTaskList_del'">新 增</el-button>
            <el-button plain :disabled="multiple" icon="Delete" type="primary" v-auth="'train_xxrwTaskList_del'" @click="handleDelete(selectObjs)">删除</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
       :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle" @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="taskId" label="学习任务id"  width="150"/>
          <el-table-column prop="taskName" label="学习任务名称"  show-overflow-tooltip/>
        <el-table-column prop="taskState" label="学习任务状态" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="xxrw_task_state" :value="scope.row.taskState"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dataQuantity" label="资料数量"  show-overflow-tooltip/>
        <el-table-column prop="orgName" label="参与组织"  show-overflow-tooltip/>
        <el-table-column prop="isTimeLimit" label="是否限时"  show-overflow-tooltip>
            <template #default="{ row }">
                <span v-if="row.isTimeLimit === 1">是</span>
                <span v-else>否</span>
            </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间"  show-overflow-tooltip/>
        <el-table-column prop="totalDuration" label="总时长(小时)"  show-overflow-tooltip/>
        <el-table-column prop="createTime" label="创建时间"  show-overflow-tooltip/>
        <el-table-column prop="taskProgress" label="学习任务进度"  show-overflow-tooltip/>
        <el-table-column label="考试详情" width="150">
          <template #default="scope">
             <el-button icon="Search" text type="primary" v-auth="'train_xxrwTaskList_del'" @click="goPage(scope.row.examId,scope.row.taskId)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="学习进度详情" width="150">
          <template #default="scope">
              <el-button text type="primary" icon="Search" @click="addkeyPoints(1,scope.row.taskId,scope.row.examId)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'train_xxrwTaskList_del'" @click="goKszlFile(1,scope.row.taskId)">编辑</el-button>
            <!--<el-button icon="edit-pen" text type="primary" v-auth="'train_xxrwTaskList_edit'" @click="formDialogRef.openDialog(scope.row.id)">编辑</el-button>-->
            <el-button icon="delete" text type="primary" v-auth="'train_xxrwTaskList_del'" @click="handleDelete([scope.row.id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>
    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
  </div>
</template>

<script setup lang="ts" name="systemXxrwTaskList">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/train/xxrwTaskList";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { deptTree } from '/@/api/train/kszlData';
import { useDict } from '/@/hooks/dict';
import { ref ,reactive, onMounted } from 'vue';
import mittBus from '/@/utils/mitt';
import { useRouter } from 'vue-router';
import { professionalnameList } from '/@/api/train/jnglProfessionLevel';


// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典
const cascadertasklist = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
const router = useRouter();
const { yes_no_type,xxrw_task_state } = useDict('yes_no_type','xxrw_task_state')
// 定义变量内容
const formDialogRef = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
//学习组织数据
const options1 = ref<any[]>([]);
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
		orgName:[]
  },
  pageList: fetchList
})
const addkeyPoints =(state:number,taskId:string,examId:string) =>{
  console.log('taskId---------',taskId)
  const path = './learning';
  const sendId1 = { state,taskId,examId }
  console.log('send1-----',sendId1)
  router.push({path, query: sendId1 })
}
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
	tableStyle
} = useTable(state)
//挂载完毕
onMounted(()=>{
  deptTreeList()
  // renderChart()
})
// const handleChange = (item :any) =>{
//     let queryName:string[] = []
//     console.log('item',item)
//     if(cascadertasklist.value) {
//         // console.log(cascadertasklist.value.getCheckedNodes()[0].pathLabels)
//         queryName.push(cascadertasklist.value.getCheckedNodes()[0].pathLabels)
//     }
//     state.queryForm.orgId = item.join('/')
//
//
//     console.log('item',item.join('/'))
// 	console.log('queryNameProxy',queryNameProxy.join('/'));
// }
const handleChange = (item: any) => {
	let queryName: string[] = [];
	console.log('item', item);
	if (cascadertasklist.value) {
		// 确保getCheckedNodes()[0]存在，并且pathLabels是一个数组
		if (cascadertasklist.value.getCheckedNodes().length > 0) {
			queryName = cascadertasklist.value.getCheckedNodes()[0].pathLabels;
		}
	}

	// 使用Proxy来包装queryName数组
	const queryNameProxy = new Proxy(queryName, {
		// 可以在这里定义Proxy的handler，比如拦截数组的某些操作
	});

	state.queryForm.orgId = item.join('/');
	state.queryForm.orgName = queryNameProxy.join('/'); // 赋值Proxy对象

	console.log('item', item.join('/'));
	console.log('queryNameProxy', queryNameProxy.join('/'));
};
// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}

// //跳转页面---------编辑state:1 新增state:0
const goKszlFile =(state:number,taskId:string) =>{
	console.log('taskId---------',taskId)
	const path = './study';
	const sendId1 = { state,taskId }
	console.log('send1-----',sendId1)
	router.push({path, query: sendId1 })
}

const goPage=(examId1:string,taskId1:string) =>{
	const examId = examId1
    const taskId = taskId1
	// console.log('sendId---------',sendId)
	const path = '/train/xxrwTranscript/index';
	const sendId1 = { examId,taskId }
	console.log(examId,'examId');
	router.push({path,query: sendId1 })
}
// 导出excel
const exportExcel = () => {
  downBlobFile('/train/xxrwTaskList/export', Object.assign(state.queryForm, { ids: selectObjs }), 'xxrwTaskList.xlsx')
}
// 参与组织
const deptTreeList = async () => {
  deptTree().then((res) => {
    options1.value = res.data;
    console.log('111、、、',res.data)
  });
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};



</script>

<style scoped>
  #canvas {
    width: 100%;
    height: 300px;
  }
  .el-row {
    margin-bottom: 20px;
  }
  .el-row:last-child {
    margin-bottom: 0;
  }
  .el-col {
    border-radius: 4px;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
</style>
